import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js';

export default function useMonaco(language = 'javascript') {
  let monacoEditor: monaco.editor.IStandaloneCodeEditor;
  let initReadOnly = false;
  const updateVal = async (val: string) => {
    monacoEditor?.setValue(val);
    setTimeout(async () => {
      initReadOnly && monacoEditor?.updateOptions({ readOnly: false });
      await monacoEditor?.getAction('editor.action.formatDocument')?.run();
      console.log('🚀 ~ file: use-monaco.ts ~ line 11 ~ setTimeout ~ monacoEditor', monacoEditor);

      initReadOnly && monacoEditor?.updateOptions({ readOnly: true });
    }, 100);
  };

  const createEditor = (el: HTMLElement, editorOption: monaco.editor.IStandaloneEditorConstructionOptions = {}) => {
    if (monacoEditor) {
      return;
    }
    initReadOnly = !!editorOption.readOnly;
    monacoEditor =
      el &&
      monaco.editor.create(el, {
        language,
        minimap: { enabled: false },
        theme: 'vs-light', // 官方自带三种主题vs, hc-black, or vs-dark
        multiCursorModifier: 'ctrlCmd',
        scrollbar: {
          verticalScrollbarSize: 8,
          horizontalScrollbarSize: 8,
        },
        tabSize: 2,
        automaticLayout: true, // 自适应宽高
        cursorStyle: 'line', //光标样式
        quickSuggestionsDelay: 100, //代码提示延时
        ...editorOption,
      });

    return monacoEditor;
  };
  const onFormatDoc = async () => {
    await monacoEditor?.getAction('editor.action.formatDocument').run();
    console.log('🚀 ~ file: use-monaco.ts ~ line 41 ~ onFormatDoc ~ monacoEditor', monacoEditor);
  };
  return {
    updateVal,
    getEditor: () => monacoEditor,
    createEditor,
    onFormatDoc,
  };
}
